//
//  MLOAuthController.swift
//  MLSina20160624
//
//  Created by manmanlang on 16/6/25.
//  Copyright © 2016年 manmanlang. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class MLOAuthController: UIViewController {
    
    override func loadView() {
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        view.backgroundColor = UIColor.whiteColor()
    }
    
    func setupUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(MLOAuthController.cancelClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(self.autoFillClick))
        navigationItem.title = "OAuth登录"
    }
    
    @objc private func autoFillClick() {
        printLog("自动填充")
        autofill()
    }
    
    // MARK: - 自动填充
    func autofill(){
        
        // 1 js -- \是转义字符
        let js = "document.getElementById('userId').value = \"18612789340\";document.getElementById('passwd').value = \"Shuai960702\""
        // 2 让web页面加载 js,
        webView.stringByEvaluatingJavaScriptFromString(js)
    }

    
    @objc private func cancelClick() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    private lazy var webView:UIWebView = {
        
        let webView = UIWebView()
        let url = NSURL(string:"https://api.weibo.com/oauth2/authorize?client_id=\(ML_AppKey)&redirect_uri=\(redirect_uri)")!
        printLog(url)
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
        webView.delegate = self
        return webView
    }()

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

// MARK: - UIWebViewDelegate
extension MLOAuthController:UIWebViewDelegate {
    ///开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    ///加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    ///加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
    ///将要加载request 返回false代表停止加载 true代表继续加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL?.absoluteString
        
        //判断urlString是否有值并且它的值前缀等于回调页
        if let u = urlString where u.hasPrefix(redirect_uri) {
            //请求参数
            let query = request.URL?.query
            if let query = query {
                let code = query.substringFromIndex("code=".endIndex)
                loadUserAccount(code)
                return false//已经获取了code 没必要加载界面了
            }
        }
        return true
    }
    
}

// MARK: - UIWebViewDelegate
extension MLOAuthController {
    
    func loadUserAccount(code:String) {
        MLNetworkTool.sharedNetworkTool.oauthLoadUserAccount(code, success: { (response) in
            //需要判断response是否有值并且它可以转成字典
            guard let response = response as? [String:AnyObject] else {
                return
            }
            let userAccount = MLUserAccount(dict: response)
            self.loadUserInfo(userAccount)
            }) { (error) in
                print(error)
        }
    }
    
    func loadUserInfo(userAccount: MLUserAccount){
        
        MLNetworkTool.sharedNetworkTool.oauthLoadUserInfo(userAccount, success: { (response) -> () in
            // 判断是否有值而且可以转成字典
            guard let res = response as? [String: AnyObject] else {
                return
            }
            
            userAccount.avatar_large = res["avatar_large"] as? String
            userAccount.screen_name = res["screen_name"] as? String
            // 通过归档保存数据
            MLUserAccountTool.sharedTool.saveUserAccount(userAccount)
//            let reuslt = MLUserAccountTool.sharedTool.userAccount//取数据
            
            //关闭加载OAuth授权界面
            self.dismissViewControllerAnimated(false, completion: {
                //关闭指示器
                SVProgressHUD.dismiss()
                
                NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootViewController, object: nil)
            })
            
        }) { (error) -> () in
            print("失败\(error)")
        }
    }
    
//     private func loadUserAccount(code:String) {
//        let urlString = "https://api.weibo.com/oauth2/access_token"
//        
//        let params = [
//            "client_id":ML_AppKey,
//            "client_secret":ML_AppSecret,
//            "grant_type":"authorization_code",
//            "code":code,
//            "redirect_uri":redirect_uri
//        ]
//        
//        let manager = AFHTTPSessionManager()
//        
//        manager.responseSerializer.acceptableContentTypes?.insert("text/plain")
//        
//        manager.POST(urlString, parameters: params, progress: nil, success: { (_, response) in
//            print(response)
//            }) { (_, error) in
//                SVProgressHUD.showErrorWithStatus("请求失败:\(error)")
//        }
//    }
    
}








